package com.lianrui.app.order.services.impl;

import static com.lianrui.message.IBusinessMessage.BIS_ADD_FAILED;
import static com.lianrui.message.IBusinessMessage.BIS_ORDER_ID_IS_NULL;
import static com.lianrui.message.IBusinessMessage.BIS_ORDER_NOT_ALLOW_CANCEL;
import static com.lianrui.message.IBusinessMessage.BIS_ORDER_NOT_EXIST;
import static com.lianrui.message.IBusinessMessage.BIS_ORDER_STATUS_IS_NULL;
import static com.lianrui.message.IBusinessMessage.BIS_PRODUCT_NOTEXISTS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lianrui.app.cart.domain.Cart;
import com.lianrui.app.cart.service.ICartService;
import com.lianrui.app.goods.service.IProductSerivce;
import com.lianrui.app.member.domain.Member;
import com.lianrui.app.member.service.IMemberService;
import com.lianrui.app.order.dao.IOrderDao;
import com.lianrui.app.order.domain.Order;
import com.lianrui.app.order.domain.OrderItem;
import com.lianrui.app.order.domain.OrderLog;
import com.lianrui.app.order.domain.OrderPrice;
import com.lianrui.app.order.money.CheckoutAdapter;
import com.lianrui.app.order.money.CheckoutAdapter.Checkout;
import com.lianrui.app.order.services.IOrderItemService;
import com.lianrui.app.order.services.IOrderService;
import com.lianrui.app.order.services.OrderStatus;
import com.lianrui.app.order.vos.OrderPage;
import com.lianrui.commons.exception.BusinessException;
import com.lianrui.commons.tools.Functions;
import com.lianrui.commons.validate.InputValidate;
import com.lianrui.core.AbstractService;
import com.lianrui.core.IDao;
import com.lianrui.core.IDao.OperateType;
import com.lianrui.message.IBusinessMessage;
import com.lianrui.web.spring.ServletUtils;

/**
 * 功能描述：订单服务实现
 *
 * @author LJQ
 *
 * 2015年12月29日 下午2:48:44
 */
@Service("orderService")
public class OrderService extends AbstractService<OrderPage, Order, Integer> implements IOrderService {
	
	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);
	
	@Autowired
	IMemberService memberService;
	@Autowired
	ICartService cartService;
	@Autowired
	IProductSerivce productSerivce;
	@Autowired
	IOrderItemService orderItemService;
	
	
	@Resource
	IOrderDao orderDao;
	
	@Override
	public IDao<OrderPage, Order, Integer> getDao() {
		return orderDao;
	}
	
	/**
	 * 修改订单状态
	 * @param orderId ： 订单id
	 * @param status ： 订单状态
	 * @throws BusinessException 
	 */
	public void updateOrderStatus(Integer orderId, Integer status) throws BusinessException{
		if(null == orderId || orderId < 0){
			throw new  BusinessException(BIS_ORDER_ID_IS_NULL, getLogger());
		}
		if(null == status){
			throw new  BusinessException(BIS_ORDER_STATUS_IS_NULL, getLogger());
		}
		else{
			Order order = orderDao.pure(orderId);
			if(null != order){
				//用户取消订单而且订单状态为已支付则不允许取消
				if(status == OrderStatus.ORDER_CANCEL){
					if(order.getStatus() == OrderStatus.ORDER_PAY && status == OrderStatus.ORDER_CANCEL){
						throw new  BusinessException(BIS_ORDER_NOT_ALLOW_CANCEL, getLogger());
					}
					else{
						order.setStatus(status);
						orderDao.updateStatus(order);
					}
				}
				
				//修改订单状态
				else{
					order.setStatus(status);
					orderDao.updateStatus(order);
				}

			}
			else{
				throw new  BusinessException(BIS_ORDER_NOT_EXIST, getLogger());
			}
		}
	
	}
	
	@Override
	@Transactional
	public void addItem(OrderItem... item) throws BusinessException {
		 orderDao.addItem(item);
	}
	
	@Override
	protected Logger getLogger() {
		return LOGGER;
	}

	@Override
	@Transactional
	public void addLog(OrderLog log) throws BusinessException {
		orderDao.addLog(log);
	}

	@Override
	public Order create(Integer productId, Integer num, Integer... cartIds) throws BusinessException {
		List<Cart> carts = new ArrayList<>();
		if (productId != null && num != null && num != 0) {
			//通过产品直接下单
			Cart cart = new Cart();
			cart.setProduct(productSerivce.unique(productId));
			cart.setNum(num);
			carts.add(cart);
		} else if (!ArrayUtils.isEmpty(cartIds)) {
			//通过购物车下单
			carts.addAll(cartService.get(cartIds));
			cartService.delete(cartIds);
		} else {
			throw new BusinessException(BIS_ADD_FAILED, LOGGER, "Order");
		}
		Map<String,Object> params = new HashMap<String, Object>();
		params.put(CheckoutAdapter.CKOUT_PARAM_CARTS, carts);
		OrderPrice orderPrice = CheckoutAdapter.checkout(Checkout.Default, params);
		
		return doCreateOrder(orderPrice, carts.toArray(new Cart[carts.size()]));
	}
	
	/**
	 * 功能说明：初始化订单信息
	 * @param order
	 * @param orderPrice
	 * @throws BusinessException 
	 */
	@Transactional
	public Order doCreateOrder(OrderPrice orderPrice, Cart... carts) throws BusinessException {
		if (ArrayUtils.isEmpty(carts)) {
			throw new BusinessException(BIS_PRODUCT_NOTEXISTS, LOGGER);
		}
		Integer member_id = (Integer) ServletUtils.getCurrentSession().getAttribute("member_id");
		if (member_id == null) {
			throw new BusinessException(IBusinessMessage.BIS_INVALID_MEMBER, getLogger());
		}
		Member member = memberService.unique(member_id);
		/************ 创建订单 ************************/
		//商品信息
		Order order = new Order();
		order.setMember_id(member.getMember_id());
		order.setGoods_amount(orderPrice.getGoodsPrice());
		order.setWeight(orderPrice.getWeight());
		order.setDiscount(orderPrice.getDiscountPrice());// 打折
		order.setOrder_amount(Functions.add(orderPrice.getOrderPrice(), order.getInvoice_amount()));// 订单价格
		order.setProtect_price(orderPrice.getProtectPrice());// 保护价格
		order.setShipping_amount(orderPrice.getShippingPrice());// 运输价格
		order.setGainedpoint(orderPrice.getPoint());
		//默认信息
		order.setShipping_type("快递");
		order.setPaymoney(0.0);
		order.setCreate_time(System.currentTimeMillis());
		order.setSn(Functions.createSN());
		order.setStatus(OrderStatus.ORDER_NOT_PAY);
		order.setDisabled(0);
		order.setPay_status(OrderStatus.PAY_NO);
		order.setShip_status(OrderStatus.SHIP_NO);
		add(order);
		
		//添加订单项
		List<OrderItem> items = new ArrayList<>();
		for (Cart cart : carts) {
			OrderItem orderItem = new OrderItem();
			orderItem.setPrice(cart.getProduct().getPrice());
			orderItem.setName(cart.getProduct().getName());
			orderItem.setNum(cart.getNum());
			orderItem.setProduct_id(cart.getProduct_id());
			orderItem.setGoods_id(cart.getProduct().getGoods_id());
			orderItem.setShip_num(0);
			orderItem.setSpec_id(cart.getProduct_id());
			orderItem.setOrder_id(order.getOrder_id());
			orderItem.setGainedpoint(orderPrice.getPoint());
			orderItem.setAddon("");
			int leiNum = Integer.parseInt(cart.getProduct().getGoods().getDefault_count_number());
			orderItem.setLeinum(leiNum);
			orderItem.setService_number(cart.getCart_id() + "");
			items.add(orderItem);
		}
		addItem(items.toArray(new OrderItem[items.size()]));
		addLog(new OrderLog(order.getOrder_id(), member.getId(), member.getName(), "订单创建", System.currentTimeMillis()));
		return unique(order.getId());
	}
	
	@Override
	public void payMobile(Integer id) throws BusinessException {
		orderDao.payMobile(id);
	}
	
	@Override
	public int validate(OperateType opType, final Order d) throws BusinessException {
		return new InputValidate(IBusinessMessage.BIS_MODEL_ORDER) {
			{
				noNull(d);
				noNull(d.getMember_id(), IBusinessMessage.BIS_FIELD_MEMBERID);
			}
		}.validate();
	}
}
